﻿using System;
using System.Collections.Generic;
using System.Text;
using Barbar.UrlGuard.Dal;
using System.Net;

namespace Barbar.UrlGuard.BL.Concrete {
  internal class WebRequestUtility : IWebRequestUtility {
    #region IWebRequestUtility Members

    public void CheckEntry(MonitoringEntry entry, int timeout) {
      if (entry == null)
        throw new ArgumentNullException("entry");

      WebRequest request = WebRequest.Create(entry.Url);
      request.Timeout = timeout;
      if (entry.Authentication != null) {
        entry.Authentication.SetWebRequest(request);
      }
      // Reset monitor entry
      entry.LastErrorMessage = string.Empty;
      entry.LastStatusCode = -1;
      DateTime startTime = DateTime.Now;
      try
      {
          using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
          {
              entry.LastStatusCode = (int)response.StatusCode;
              entry.LastRequestLength = DateTime.Now.Subtract(startTime).TotalMilliseconds;
          }
      }
      catch (WebException webException)
      {
          entry.LastErrorMessage = "[HTTP Request Failed] " + webException.Message;
      }
    }

    #endregion
  }
}
